package com.liuxl.core.controller.gen;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import io.swagger.annotations.Api;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageInfo;
import com.liuxl.core.common.base.BaseController;
import com.liuxl.core.common.conf.V2Config;
import com.liuxl.core.common.domain.AjaxResult;
import com.liuxl.core.common.file.FileUtils;
import com.liuxl.core.common.log.PathLogDefiner;
import com.liuxl.core.model.auto.TsysDatas;
import com.liuxl.core.model.auto.TsysFile;
import com.liuxl.core.model.custom.TableSplitResult;
import com.liuxl.core.model.custom.Tablepar;
import com.liuxl.core.model.custom.TitleVo;

import cn.hutool.core.io.FileUtil;
import cn.hutool.http.HttpUtil;

/**
 * 文件上传controller
 * @date: 2018年9月16日 下午4:23:50
 */
@Controller
@Api(value = "文件上传")
@RequestMapping("FileUtilController")
public class FileUtilController extends BaseController{

	
    /**
     * Java 上传文件
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file)
    {
    	Map<String,Object> map = new HashMap<String,Object>();
        try
        {
        	System.out.println(!file.isEmpty());
            if (!file.isEmpty())
            {
                //插入文件存储表
            	String id=sysDatasService.insertSelective(file);
                if(id!=null){
                	map.put("id", id);
                	map.put("filename", file.getOriginalFilename());
                	return AjaxResult.successData(200, map);
                }
            }
            return error();
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }
	
    /**
     * node 模式 -上传文件
     * @throws IOException 
     * @throws IllegalStateException 
     */
    @PostMapping("/uploadByNode")
    @ResponseBody
    public AjaxResult uploadByNode(@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException
    {
    	Map<String,Object> map = new HashMap<String,Object>();
    	
        try
        {
        	//插入文件存储表
        	String id=sysDatasService.insertSelectiveBynode(file);
            if(id!=null){
            	map.put("id", id);
            	map.put("filename", file.getOriginalFilename());
            	return AjaxResult.successData(200, map);
            }
        	
            return error();
        }
        catch (Exception e)
        {
            return error(e.getMessage());
        }
    }
	

    @RequestMapping("/downloadFile/{id}")
    public void downLoad(@PathVariable("id") String id,HttpServletResponse response,HttpServletRequest request) throws Exception{
    	TsysDatas sysDatas = sysDatasService.selectByPrimaryKey(id);
    	String fileNames = new String(sysDatas.getFilePath().getBytes(), "ISO-8859-1"); 
    	String temp_dir="/elitetemp/";
    	if(PathLogDefiner.isLinux()) {
    		temp_dir = "/home/elitetemp/";
		}else if(PathLogDefiner.isWindows()){
			temp_dir = "C:/elitetemp/";
		}
    	
        File file;
        String url ="";
    	if("U".equals(V2Config.getIsstatic())) {//获取根目录
    		url = V2Config.getNodeurl() + "/upliu/file/" + sysDatas.getFilePath();
    		System.out.println("url:::"+url);
    		long size = HttpUtil.downloadFile(url, FileUtil.file(temp_dir+fileNames));
    		System.out.println("Download size: " + size);
    		file = new File(temp_dir + fileNames);
    	}else if("N".equals(V2Config.getIsstatic())){
    		url = V2Config.getProfile() + "/" + sysDatas.getFilePath();
    		file = new File(url);
	   	}else {
	   		StringBuffer requestURL = request.getRequestURL();
	   		String uul = requestURL.toString().split(request.getContextPath())[0];
	   		url = uul+"/"+request.getContextPath()+"/"+V2Config.getIsroot_dir()+"/"+fileNames;
	   		long size = HttpUtil.downloadFile(url, FileUtil.file(temp_dir+fileNames));
	   		System.out.println("Download size: " + size);
	   		file = new File(temp_dir + fileNames);
	   	}
        if(file.exists()){ //判断文件父目录是否存在
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileNames);
            
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file); 
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download--" + sysDatas.getFilePath());
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    /**
     * data 目录下的模板下载功能示例
     * 1：sbqd    2：szmx  3：zcfz
     * @param id 
     * @param response
     * @throws Exception
     */
    @RequestMapping("/downloadFileMoudule/{id}")
    public void downloadFileMoudule(@PathVariable("id") String id,HttpServletResponse response) throws Exception{
    	
    	String path = "/static/data/"+id+".xlsx";
        File file = new File(ResourceUtils.getURL("classpath:").getPath() + path);
        if(file.exists()){ //判断文件父目录是否存在
        	String realname = "";
        	if("sbqd".equals(id)) {
        		realname  = "设备清单.xlsx";
        	}else if("szmx".equals(id)) {
        		realname  = "收支明细表.xlsx";
        	}else if("zcfz".equals(id)) {
        		realname  = "资产负债表.xlsx";
        	}
        	String fileNames = new String(realname.getBytes(), "ISO-8859-1"); 
            response.setContentType("application/force-download");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileNames);
            
            byte[] buffer = new byte[1024];
            FileInputStream fis = null; //文件输入流
            BufferedInputStream bis = null;
            
            OutputStream os = null; //输出流
            try {
                os = response.getOutputStream();
                fis = new FileInputStream(file); 
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while(i != -1){
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("----------file download--" + fileNames);
            try {
                bis.close();
                fis.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    
    
}
